/*
 * @Date: 2022-02-27 23:20:12
 * @LastEditors: zhaoxm
 * @LastEditTime: 2022-09-08 13:52:12
 * @Description: 动态更换html中的差值表达式
 */

import { getViteEnv as getViteEnvironment } from "./utils"

export function vitePluginHtml() {
  return {
    name: "vite-plugin-html",
    transformIndexHtml(html, context) {
      const environmentConfig = context.server
        ? getViteEnvironment(context.server.config.mode)
        : getViteEnvironment("production")
      const reg = /{{(.*)}}/g
      return html.replace(reg, (match, key) => {
        key = key.trim()
        return environmentConfig[key] || match
      })
    },
  }
}
